package cn.util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	static SqlSession session=null;
	static SqlSessionFactory sqlSessionFactory=null;
	static{
		if(sqlSessionFactory==null){
			try {
				SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
				//加载核心配置文件
				sqlSessionFactory=sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static SqlSession getSession(){
		//获取session
		session=sqlSessionFactory.openSession(true);
		return session;
	}
	
	public static void closeSession(){
		if(session!=null){
			session.close();
		}
	}

	public static void main(String[] args) {
		MyBatisUtil.getSession();
	}
}
